import { loginApi } from '../http/userApi'

export default {
  namespaced: true,
  state: {
    // 如果本地中有就取本地，否则为 undefined 或者 null
    username: localStorage.getItem('username'),
    userId: localStorage.getItem('userId'),
    token: localStorage.getItem('token')
  },
  getters: {
  },
  mutations: {
    loginMutation(state, user) {
      state.username = user.username;
      state.userId = user.userId;
      state.token = user.token
    },
    logoutMutation(state) {
      state.username = null;
      state.userId = null;
      state.token = null;
    }
  },
  actions: {
    loginAction({ commit }, user) {
      return new Promise((resolve, reject) => {
        loginApi(user.username, user.password)
          .then(res => {
            console.log(res.data)
            commit('loginMutation', {
              username: user.username,
              userId: res.data.data.userId,
              token: res.data.data.token
            });

            // 存入本地存储
            localStorage.setItem('username', user.username);
            localStorage.setItem('userId', res.data.data.userId);
            localStorage.setItem('token', res.data.data.token);

            resolve();
          })
          .catch(err => {
            reject(err);
          })
      })
    },
    logoutAction({ commit }) {
      return new Promise((resolve) => {
        commit('logoutMutation');
        localStorage.clear();
        resolve();
      })
    }
  },
}